
function DWR() { }
DWR.setErrorHandler = function(handler) {
	DWR._errorHandler = handler;
};

DWR._errorHandler = function(message,async) {
	var msg = message;
	if (typeof message == "object" && message.name == "Error" && message.description) {
		msg = message.description;
	}
	if (msg == "session time out"){
		showWarning("操作员登录超时，请重新登录！");
		returnToLogin();
	}else{
		if(!async){
			throw new Error(msg + "");
		}
		else{
			showError(msg);
		}
	}
};
DWR._verb = "POST";
DWR._async = true;
DWR._timeout = 0;
DWR._DOMDocument = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];
DWR._XMLHTTP = ["Msxml2.XMLHTTP","Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];

//call action
DWR.syncCall = function(actionName) {
	if (!actionName)
		throw new Error("must provide actionName")
	var args = arguments;
	var c = {}
	
	var lastArgIndex = args.length -1;
	
	var ss = actionName.split('.')
	var path = contextRoot + "d/dwr/"+ss[0]
	if (ss[1]) path+="/"+ss[1]
	c.path = path;
	c.verb = DWR._verb;
	c.timeout = DWR._timeout;
	c.async = false;
	c.directreturn = true;
	c.map = {};

	for (var i = 1; i <= lastArgIndex; i++) {
		if (args[i]){
			c.map['p'+(i-1)] = args[i].toJSONString();
		}		
	}
	c.completed = false;
	
	return DWR._sendData(c);
};

DWR.call = function(actionName) {
	if (!actionName)
		throw new Error("must provide actionName")
	var args = arguments;
	var c;
	
	var lastArg = args[args.length - 1];
	var lastArgIndex = args.length -1;
	if (args.length==1){
		c = {}
	}
	else if (typeof lastArg == "function") {
		c = { callback:lastArg };
		lastArgIndex = args.length - 2;
	}
	else if (typeof lastArg == "object"){
	
		var last2Arg 
		if (args.length>=2)
			last2Arg = args[args.length - 2];
		if (typeof last2Arg == "function") {
			c = lastArg;
			c.callback = last2Arg;
			lastArgIndex = args.length - 3;
		}
		else {
			c = {}
		}
	}
	else c = {}
	var ss = actionName.split('.')
	var path = contextRoot + "d/dwr/"+ss[0]
	if (ss[1]) path+="/"+ss[1]
	c.path = path;
	if (c.verb == null) {
		c.verb = DWR._verb;
	}
	if (c.async == null) {
		c.async = DWR._async;
	}
	if (c.timeout == null) {
		c.timeout = DWR._timeout;
	}
	c.map = {};

	for (var i = 1; i <= lastArgIndex; i++) {
		if (args[i]){
//			alert("args["+i+"]="+args[i])
//			alertAll(args[i])
			c.map['p'+(i-1)] = args[i].toJSONString();
		}		
	}
	c.completed = false;
	if(c.blockScreen){
		Loading.blockScreen();
	}
	else{
		var cObj = c.disCtrl;
		if (cObj){
			if(cObj.length){
				if(cObj.length > 0){
					for(var j=0;j<cObj.length;j++){
						cObj[j].disabled=true;
					}
				}
			}
			else{
				cObj.disabled=true;
			}
		}
		if(c.loading)Loading.addLoading(c.loading);
	}
	DWR._sendData(c);
};

DWR._sendData = function( c) {

	if (c.timeout && c.timeout != 0) {
		c.interval = setInterval(function() {
			clearInterval(c.interval);
			DWR._abortRequest(c);
		}, c.timeout);
	}

	if (window.XMLHttpRequest) {
		c.req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject && !(navigator.userAgent.indexOf('Mac') >= 0 && navigator.userAgent.indexOf("MSIE") >= 0)) {
		c.req = DWR._newActiveXObject(DWR._XMLHTTP);
	}
	if (c.async) {
		c.req.onreadystatechange = function() {
			DWR._stateChange(c);
		};
	}
		
	var query = "";
	var prop;
		
	for (prop in c.map) {
			if (typeof c.map[prop] != "function") {
				query += prop + "=" + encodeURIComponent(c.map[prop]) + "&";
			}
		}
	try {
		if (c.verb=="GET") {
			c.req.open("GET",c.path+(query==""?"":'?'+query), c.async);
			c.req.setRequestHeader('Content-Type', 'text/plain');
			c.req.send(null);
		}else{
			c.req.open("POST", c.path, c.async)
			c.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
       		c.req.send(query);
		}
		if (!c.async) {
			 return DWR._stateChange(c);
		}
	}
	catch (ex) {
		DWR._errorHandler(ex,c.async);
	}
	
};

DWR._stateChange = function(c) {
	if (!c.completed && c.req.readyState == 4) {
		try {
			var reply = c.req.responseText;
			if (reply == null || reply == "") {
				alert( "网络连接超时，请检查网络状况后重试");
				return;
			}
			var status = c.req.status;
			if (status != 200) {
				if (reply == null) reply = "Unknown error occured";
				DWR._errorHandler(reply,c.async);
				return;
			}
		
			var obj;
			eval('obj='+reply)
			if (obj&&obj._error){
				DWR._errorHandler(obj._error,c.async)
			}
			else {
				if (c.directreturn){
					return obj
				}
				DWR._handleResponse(c,obj);
			}
			
		} catch (ex) {
			if (ex == null) ex = "Unknown error occured";
			DWR._errorHandler(ex,c.async);
		}
		finally {
			if (c.finalFunc){
				try {
					c.finalFunc();
				}
				catch (ex) {
					DWR._errorHandler(ex,c.async);
				}
			}
			
			if(c.blockScreen){
				Loading.cancelBlockScreen();
			}
			var cObj = c.disCtrl;
			if (cObj){
				if(cObj.length){
					if(cObj.length > 0){
						for(var j=0;j<cObj.length;j++){
							cObj[j].disabled=false;
						}
					}
				}
				else{
					cObj.disabled=false;
				}
			}
			if(c.loading)Loading.removeLoading(c.loading);
			
			DWR._clearUp(c);
		}
	}
};

DWR._handleResponse = function(c, reply) {
	
	if (c) {
		try {
			if (c.callback) c.callback(reply);
		}
		catch (ex) {
			DWR._errorHandler(ex,c.async);
		}
	}
};


DWR._abortRequest = function(c) {
	if (c && !c.completed) {
		DWR._clearUp(c);
		if (c.req) c.req.abort();
		
		DWR._errorHandler("Timeout",c.async);
	}
};


DWR._clearUp = function(c) {
	if (c.req) delete c.req;
	c.completed = true;
};


DWR._newActiveXObject = function(axarray) {
	var returnValue;
	for (var i = 0; i < axarray.length; i++) {
		try {
			returnValue = new ActiveXObject(axarray[i]);
			break;
		}
		catch (ex) {
		}
	}
	return returnValue;
};
if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function () {
        var a = ['['],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

        function p(s) {

// p accumulates text fragments in an array. It inserts a comma before all
// except the first fragment.

            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects thats lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;

// Otherwise, serialize the value.

            case 'string':
				p('\''+v.toJSONString()+'\'');break;
            case 'number':
            case 'boolean':
                p(v.toJSONString());

// Values without a JSON representation are ignored.

            }
        }

// Join all of the fragments together and return.

        a.push(']');
        return a.join('');
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {
        return getTime();
    };
    
DWR.SLASHREG = new RegExp("\\\\","gm");
DWR.QUOTEREG = new RegExp("'","gm");
 	String.prototype.toJSONString = function () {
 		var s = this.replace(DWR.SLASHREG,"\\\\");
 		s = s.replace(DWR.QUOTEREG,"\\'");
 		return s;
    };
	
    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : "null";
    };


    Object.prototype.toJSONString = function () {
        var a = ['{'],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            k,          // The current key.
            v;          // The current value.

        function p(s) {

// p accumulates text fragment pairs in an array. It inserts a comma before all
// except the first fragment pair.

            if (b) {
                a.push(',');
            }
            a.push(k, ':', s);
            b = true;
        }

// Iterate through all of the keys in the object, ignoring the proto chain.

        for (k in this) {
            if (this.hasOwnProperty(k)) {
                v = this[k];
                switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;

                case 'string':
					p('\''+v.toJSONString()+'\'');break;
                case 'number':
                case 'boolean':
                    p(v.toJSONString());

// Values without a JSON representation are ignored.

                }
            }
        }

// Join all of the fragments together and return.

        a.push('}');
        return a.join('');
    };
}